package top.yfq.multidatasource.tenant;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yfq
 * @date 2025/9/26 22:56
 * @description
 */
@SuppressWarnings("all")
public class TenantInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantId = request.getHeader("Tenant-ID");

        if (StringUtils.isEmpty(tenantId)) return true;

        TenantContextHolder.setTenantId(Long.parseLong(tenantId));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantContextHolder.clear();
    }
}
